<!DOCTYPE html>
<html lang="zh-cn" dir="i18n">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- SEO -->
    <meta name="keywords" content="">
    <meta name="description" content="">

    <!-- Robots -->
    <meta name="robots" content="index,follow">
    <meta name="googlebot" content="index,follow">

    <!-- Render -->
    <meta name="renderer" content="webkit">
    <meta name="format-detection" content="telephone=no">
    <meta name="theme-color" content="#ffffff">
    <meta name="generator" content="codekit" />

    <!-- Control -->
    <meta http-equiv="Cache-Control" content="no-cache">
    <meta http-equiv="x-dns-prefetch-control" content="off">

    <!-- Favicon -->
    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="bookmark" href="../favicon.ico" type="image/x-icon">

    <!-- Third Party -->
    <link crossorigin="anonymous" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" href="//lib.baomitu.com/twitter-bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet">
    <link crossorigin="anonymous" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" href="//lib.baomitu.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../lib/shards/shards.min.css">

    <!-- User Defined -->
    <link href="../css/app.min.css" rel="stylesheet">
    <script src="../js/init.min.js"></script>

    <title>星云宝</title>
</head>

<body>
    <div class="app">
        <!-- app header -->
        <div class="app-header bg-dark">
            <div class="container">
                <!-- Navigation -->
                <nav class="navbar navbar-expand-md navbar-dark px-0">
                    <a href="../" class="navbar-brand"><img src="../images/logo-white.png" width="30" height="30" class="mr-2" alt="" data-i18n="nebpay-name">星云宝</a>

                    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar-collapse"><span class="navbar-toggler-icon"></span></button>

                    <div id="navbar-collapse" class="collapse navbar-collapse">
                        <ul class="navbar-nav mr-auto">
                            <li class="nav-item">
                                <a class="nav-link" href="../">首页</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link active" href="./initial.html">安全交易</a>
                            </li>
                        </ul>
                        <ul class="navbar-nav">
                            <li id="change-chainnet" class="nav-item dropdown d-none">
                                <a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown"></a>
                                <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                                    <a class="dropdown-item" href="javascript:" data-chainnet="mainnet">主网</a>
                                    <a class="dropdown-item" href="javascript:" data-chainnet="testnet">测试网</a>
                                </div>
                            </li>
                        </ul>
                    </div>
                </nav>
                <!-- / Navigation -->
            </div>
        </div>

        <!-- app subnav -->
        <div class="app-subnav">
            <div class="container">
                <nav class="nav">
                    <a class="nav-link" href="./initial.html">发起交易</a>
                    <a class="nav-link" href="./all.html">交易列表</a>
                    <a class="nav-link active" href="./handle.html">处理交易</a>
                    <span class="align-items-center px-4 text-light d-none d-md-flex">|</span>
                    <a class="nav-link" href="./help.html">帮助说明 ?</a>
                </nav>
            </div>
        </div>

        <!-- app body -->
        <div class="app-body mt-4">
            <div class="container">
                <div id="transaction-search-wrapper" class="d-none mb-5">
                    <div class="text-center">
                        <h3>处理交易</h3>
                        <p>交易哈希可以查询交易信息，包含等待上链和已经打包的交易。在交易打包验证时需要多次刷新查询交易的打包状态变更。</p>
                        <input name="hash" type="text" class="form-control form-control-lg rounded-0 text-center" placeholder="交易Hash" autofocus>
                    </div>
                    <div class="form-group mt-4 mb-0 text-center">
                        <button id="view-transaction" type="button" class="btn btn-dark btn-lg rounded-0">查询交易</button>
                    </div>
                </div>
                <div id="result" style="min-height: 25rem"></div>
            </div>
        </div>

        <!-- app footer -->
        <footer class="pt-5 pb-4">
            <div class="container text-center">
                <hr class="mt-0">
                <ul class="nav justify-content-center">
                    <li class="nav-item">
                        <a class="nav-link" href="../">主页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="../about.html">关于</a>
                    </li>
                </ul>
                <p class="text-muted m-0">本站基于
                    <a href="https://nebulas.io" target="_blank">Nebulas.io</a> 平台，支持移动端自适应式布局</p>
                <p class="text-muted m-0">Copyright © 2018. Created By KYW & Viggo.Gao. 由
                    <a href="https://gitee.com" target="_blank">Gitee</a> 提供站点托管,
                    <a href="https://cdn.baomitu.com/" target="_blank">Baomitu</a> 提供静态资源CDN
                </p>
            </div>
        </footer>
    </div>

    <!-- tempate -->
    <script id="tpl-result" type="text/html">
        <div class="card card-small border-secondary">
            <div class="card-body">
                <div class="table-responsive">
                    <h4 class="text-center">交易信息</h4>
                    <table class="table table-hover table-bordered table-tx-detail">
                        <tbody>
                            <tr>
                                <th style="width:10rem">交易Hash</th>
                                <td><span>{{tx.detail.hash}}</span></td>
                            </tr>
                            <tr>
                                <th>交易状态</th>
                                <td class="font-weight-bold">{{tx.detail.state | toState}}</td>
                            </tr>
                            <tr>
                                <th>付款方</th>
                                <td>{{tx.detail.from}}</td>
                            </tr>
                            <tr>
                                <th>收款方</th>
                                <td>{{tx.detail.to}}</td>
                            </tr>
                            <tr>
                                <th>交易金额</th>
                                <td>{{tx.detail.txAmount | toNas}} Nas</td>
                            </tr>
                            <tr>
                                <th>合约内交易余额</th>
                                <td>{{tx.detail.txBalance | toNas}} Nas</td>
                            </tr>
                            <tr>
                                <th>交易开始时间</th>
                                <td>{{ if tx.detail.txStart == 0 }}-
                                    {{else}}{{tx.detail.txStart | toDayjs}}{{/if}}
                                </td>
                            </tr>
                            <tr>
                                <th>交易周期</th>
                                <td>{{tx.detail.txDuration}} 天</td>
                            </tr>
                            <tr>
                                <th>创建时间</th>
                                <td>{{tx.detail.createdAt | toDayjs}}</td>
                            </tr>
                            <tr>
                                <th>更新时间</th>
                                <td>{{tx.detail.updatedAt | toDayjs}}</td>
                            </tr>
                            <tr>
                                <th>完成时间</th>
                                <td>{{ if tx.detail.closedAt == 0 }}-
                                    {{else}}{{tx.detail.closedAt | toDayjs}}{{/if}}
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    <h4 class="text-center  mt-4">纠纷信息</h4>
                    <table class="table table-hover table-tx-detail table-bordered">
                        <!-- <thead class="bg-light">
                            <tr>
                                <th scope="col" style="width:10rem">纠纷信息</th>
                                <th scope="col"></th>
                            </tr>
                        </thead> -->
                        <tbody>
                            <tr>
                                <th style="width:10rem">纠纷协商开始时间</th>
                                <td>{{ if tx.detail.disputeStart == 0 }}-
                                    {{else}}{{tx.detail.disputeStart | toDayjs}}{{/if}}
                                </td>
                            </tr>
                            <tr>
                                <th>合约内保证金余额</th>
                                <td>{{tx.detail.marginBalance | toNas}} Nas</td>
                            </tr>
                            <tr>
                                <th>纠纷协商周期</th>
                                <td>{{tx.detail.disputeDuration}} 天</td>
                            </tr>
                            <tr>
                                <th>保证金最低缴纳数</th>
                                <td>{{tx.detail.marginAmount | toNas}} Nas</td>
                            </tr>
                        </tbody>
                    </table>
                    <h4 class="text-center mt-4">往来记录</h4>
                    <table class="table table-hover table-bordered">
                        <thead class="bg-light">
                            <tr>
                                <th scope="col">来源地址</th>
                                <th scope="col">目的地址</th>
                                <th scope="col">转账金额</th>
                                <th scope="col">时间</th>
                            </tr>
                        </thead>
                        <tbody>
                            {{if tx.transfers.length > 0}}{{each tx.transfers}}
                            <tr>
                                <td>{{$value.from}}</td>
                                <td>{{$value.to}}</td>
                                <td>{{$value.value | toNas}} Nas</td>
                                <td>{{$value.timestamp | toDayjs}}</td>
                            </tr>
                            {{/each}}
                            {{else}}
                                <tr>
                                    <td colspan="4">暂无记录</td>
                                </tr>
                                {{/if}}
                        </tbody>
                    </table>
                    <h4 class="text-center mt-4">操作记录</h4>
                    <table class="table table-hover table-bordered">
                        <thead class="bg-light">
                            <tr>
                                <th scope="col">操作者地址</th>
                                <th scope="col">操作</th>
                                <th scope="col">时间</th>
                            </tr>
                        </thead>
                        <tbody>
                            {{if tx.events.length > 0}}{{each tx.events}}
                            <tr>
                                <td>{{$value.operator}}</td>
                                <td>{{$value.content | toEvent}}</td>
                                <td>{{$value.timestamp | toDayjs}}</td>
                            </tr>
                            {{/each}}
                            {{else}}
                                <tr>
                                    <td colspan="4">暂无记录</td>
                                </tr>
                                {{/if}}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        {{if tx.detail.state == 'init'}}
        <div class="row">
            <div class="col mt-4">
                <div class="card card-small border-primary">
                    <div class="card-body text-center">
                        <h4 class="card-title text-primary">付款方处理</h4>
                        <p class="card-text text-primary mb-3">付款方发起安全交易，收款方确认前可取消本次交易</p>
                        <button class="btn btn-primary btn-block mt-2" onclick="contractCall('fromCancel','{{tx.detail.hash}}')"><strong>取消交易</strong><br><small>（仅当付款方操作时有效）</small></button>
                    </div>
                </div>
            </div>
            <div class="col mt-4">
                <div class="card card-small border-danger">
                    <div class="card-body text-center">
                        <h4 class="card-title text-danger">收款方处理</h4>
                        <p class="card-text text-danger mb-3">付款方发起安全交易，等待收款方确认</p>
                        <button class="btn btn-danger btn-block" onclick="contractCall('toComfirm','{{tx.detail.hash}}')"><strong>确认交易</strong><br><small>（仅当收款方操作时有效）</small></button>
                    </div>
                </div>
            </div>
        </div>
        {{else if tx.detail.state == 'underway' && !isExpired(tx.detail.txStart, tx.detail.txDuration)}}
        <div class="card card-small border-primary mt-4">
            <div class="card-body text-center">
                <h4 class="card-title text-primary">付款方处理</h4>
                <p class="card-text text-primary mb-3">收款方已确认交易，付款方可确认支付或申请退款</p>
                <button class="btn btn-primary btn-block" onclick="contractCall('fromComfirm','{{tx.detail.hash}}')"><strong>确认支付</strong><br><small>（仅当付款方操作时有效）</small></button>
                <button class="btn btn-warning btn-block mt-2" onclick="contractCall('fromRefund','{{tx.detail.hash}}')"><strong>申请退款</strong><br><small>（仅当付款方操作时有效）</small></button>
            </div>
        </div>

        {{else if tx.detail.state == 'underway' && isExpired(tx.detail.txStart, tx.detail.txDuration)}}
        <div class="card card-small border-danger mt-4">
            <div class="card-body text-center">
                <h4 class="card-title text-danger">收款方处理</h4>
                <p class="card-text text-danger mb-3">交易周期已超时，收款方可收取本次交易账款</p>
                <button class="btn btn-danger btn-block" onclick="contractCall('toReceive','{{tx.detail.hash}}')"><strong>确认收款</strong><br><small>（仅当收款方操作时有效）</small></button>
            </div>
        </div>

        {{else if tx.detail.state == 'refund' && !isExpired(tx.detail.disputeStart, tx.detail.disputeDuration)}}
        <div class="card card-small border-danger mt-4">
            <div class="card-body text-center">
                <h4 class="card-title text-danger">收款方处理</h4>
                <p class="card-text text-danger mb-3">付款方已申请退款，收款方可确认退款或申请纠纷协商</p>
                <button class="btn btn-danger btn-block" onclick="contractCall('toRefundComfirm', '{{tx.detail.hash}}')"><strong>确认退款</strong><br><small>（仅当收款方操作时有效）</small></button>
                <button class="btn btn-warning btn-block mt-2" onclick="contractCall('toDoNegotiate', '{{tx.detail.hash}}', {{tx.detail.marginAmount | toNas}})"><strong>申请纠纷协商</strong><br><small>（仅当收款方操作时有效）</small></button>
            </div>
        </div>

        {{else if (tx.detail.state == 'refund' ||  tx.detail.state == 'from.negotiate') && isExpired(tx.detail.disputeStart, tx.detail.disputeDuration)}}
        <div class="card card-small border-primary mt-4">
            <div class="card-body text-center">
                <h4 class="card-title text-primary">付款方处理</h4>
                <p class="card-text text-primary mb-3">纠纷协调周期已超时，付款方可收回账款及保证金</p>
                <button class="btn btn-primary btn-block" onclick="contractCall('fromReceiveNegotiate','{{tx.detail.hash}}')"><strong>收回账款及保证金</strong><br><small>（仅当付款方操作时有效）</small></button>
            </div>
        </div>

        {{else if tx.detail.state == 'to.negotiate' && !isExpired(tx.detail.disputeStart, tx.detail.disputeDuration)}}
        <div class="card card-small border-primary mt-4">
            <div class="card-body text-center">
                <h4 class="card-title text-primary">付款方处理</h4>
                <p class="card-text text-primary mb-3">收款方已申请纠纷协商，付款方可接受协商或再次申请纠纷协商</p>
                <button class="btn btn-primary btn-block" onclick="contractCall('fromAcceptNegotiate ', '{{tx.detail.hash}}')"><strong>接受协商</strong><br><small>（仅当付款方操作时有效）</small></button>
                <button class="btn btn-warning btn-block mt-2" onclick="contractCall('fromDoNegotiate', '{{tx.detail.hash}}', {{tx.detail.marginAmount | toNas}})"><strong>申请纠纷协商</strong><br><small>（仅当付款方操作时有效）</small></button>
            </div>
        </div>

        {{else if tx.detail.state == 'to.negotiate' && isExpired(tx.detail.disputeStart, tx.detail.disputeDuration)}}
        <div class="card card-small border-danger mt-4">
            <div class="card-body text-center">
                <h4 class="card-title text-danger">收款方处理</h4>
                <p class="card-text text-danger mb-3">纠纷协调周期已超时，收款方可收回账款及保证金</p>
                <button class="btn btn-danger btn-block" onclick="contractCall('toReceiveNegotiate','{{tx.detail.hash}}')"><strong>收回账款及保证金</strong><br><small>（仅当收款方操作时有效）</small></button>
            </div>
        </div>

        {{else if tx.detail.state == 'from.negotiate' && !isExpired(tx.detail.disputeStart, tx.detail.disputeDuration)}}
        <div class="card card-small border-danger mt-4">
            <div class="card-body text-center">
                <h4 class="card-title text-danger">收款方处理</h4>
                <p class="card-text text-danger mb-3">付款方已申请纠纷协商，收款方可接受协商或再次申请纠纷协商</p>
                <button class="btn btn-danger btn-block" onclick="contractCall('toAcceptNegotiate ','{{tx.detail.hash}}')"><strong>接受协商</strong><br><small>（仅当收款方操作时有效）</small></button>
                <button class="btn btn-warning btn-block mt-2" onclick="contractCall('{{tx.detail.hash}}', {{tx.detail.marginAmount | toNas}})"><strong>申请纠纷协商</strong><br><small>（仅当收款方操作时有效）</small></button>
            </div>
        </div>

        {{else}}
            <div class="card card-small border-secondary mt-4">
                <div class="card-body text-center">
                    <h4 class="card-title m-0">交易本次已完结</h4>
                </div>
            </div>
            {{/if}}


    </script>

    <!-- Third Party -->
    <script crossorigin="anonymous" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" src="//lib.baomitu.com/jquery/3.3.1/jquery.slim.min.js"></script>
    <script crossorigin="anonymous" integrity="sha384-lZmvU/TzxoIQIOD9yQDEpvxp6wEU32Fy0ckUgOH4EIlMOCdR823rg4+3gWRwnX1M" src="//lib.baomitu.com/twitter-bootstrap/4.1.0/js/bootstrap.bundle.min.js"></script>

    <script src="../lib/shards/shards.min.js"></script>
    <script src="../lib/neb/nebulas.min.js"></script>
    <script src="../lib/nebpay/nebPay.min.js"></script>

    <!-- User Defined -->
    <script src="../js/tools.min.js"></script>
    <script src="../js/global.min.js"></script>
    <script>
        var Nebulas = require('nebulas'),
            Neb = Nebulas.Neb,
            Unit = Nebulas.Unit,
            Utils = Nebulas.Utils;

        var neb = new Neb();
        neb.setRequest(new Nebulas.HttpRequest(app.config.host));

        var NebPay = require('nebpay'),
            nebPay = new NebPay();
        var serialNumber; //交易序列号
        var intervalQuery; //定时查询清除器
        var nebPayOptions = {
            qrcode: {
                showQRCode: false
            },
            callback: app.config.payApi, //在测试网查询
            listener: listener
        };

        template.defaults.imports.toNas = function(value) {
            return Unit.fromBasic(Utils.toBigNumber(value), 'nas').toNumber();
        };
        template.defaults.imports.toState = function(value) {
            switch (value) {
                case 'init':
                    return '付款方发起安全交易，等待收款方确认';
                case 'underway':
                    return '收款方已确认交易，等待付款方确认支付';
                case 'refund':
                    return '付款方申请退款，等待收款方确认';
                case 'to.negotiate':
                    return '收款方发起纠纷协商，等待付款方确认';
                case 'from.negotiate':
                    return '付款方发起纠纷协商, 等待收款方确认';
                default:
                    return '交易完成';
            }
        };
        template.defaults.imports.toEvent = function(value) {
            switch (value) {
                case 'fromCreate':
                    return '付款方发起安全交易';
                case 'fromCancel':
                    return '付款方取消交易';
                case 'fromComfirm':
                    return '付款方确认支付';
                case 'fromRefund':
                    return '付款方申请退款';
                case 'fromDoNegotiate':
                    return '付款方申请纠纷协商';
                case 'fromAcceptNegotiate':
                    return '付款方接受纠纷协商';
                case 'fromReceiveNegotiate':
                    return '付款方收回纠纷协商超时退款';
                case 'toComfirm':
                    return '收款方确认交易';
                case 'toReceive':
                    return '收款方收取交易超时付款';
                case 'toRefundComfirm':
                    return '收款方确认退款';
                case 'toDoNegotiate':
                    return '收款方申请纠纷协商';
                case 'toAcceptNegotiate':
                    return '收款方接受纠纷协商';
                case 'toReceiveNegotiate':
                    return '收款方收回纠纷协商超时退款';
                default:
                    return '默认操作';
            }
        };
        template.defaults.imports.toDayjs = function(value) {
            return dayjs(new Date(value * 1000)).format('YYYY-MM-DD HH:mm:ss');
        };
        template.defaults.imports.isExpired = function(start, duration) {
            // 交易必须超过 有效周期 才可以操作
            var deadline = Utils.toBigNumber(duration).times(86400).plus(start);
            // deadline = Utils.toBigNumber(100);
            var now = Utils.toBigNumber(Date.parse(new Date())).dividedBy(1000);
            if (deadline.lte(now)) {
                return true;
            }
            return false;
        }

        // 获取交易详情
        function getTransaction(hash) {
            NProgress.start();
            var from = app.config.dappAddress;
            var dappAddress = app.config.dappAddress;
            var value = 0;
            var nonce = 0;
            var gasPrice = 1000000;
            var gasLimit = 2000000;
            var contract = {
                function: 'getTx',
                args: JSON.stringify([hash])
            }

            NProgress.set(0.3);
            neb.api.call(from, dappAddress, value, nonce, gasPrice, gasLimit, contract).then(function(resp) {
                var result = JSON.parse(resp.result)
                // console.log(result);
                if (result && result.code < 20000) {
                    $('#result').html(template.render($('#tpl-result').html(), {
                        tx: result.data
                    }));
                } else if (result.code === 20001) {
                    swal('错误', '交易未找到', 'error');

                }
                NProgress.done();
            }).catch(function(error) {
                console.log("error:" + error.message)
            });
        }

        function contractCall(funcName, hash, value) {
            value = value || 0;

            swal({
                title: "确认执行该操作吗？",
                text: "请确认你具有该操作的权限！同时该操作将会调用【星云钱包】，并消耗很少数量的Nas手续费。",
                icon: "warning",
                buttons: true,
                dangerMode: true,
            }).then(function(wannaDo) {
                if (!wannaDo) {
                    return;
                }
                serialNumber = nebPay.call(app.config.dappAddress, value, funcName, JSON.stringify([hash]), nebPayOptions);

                intervalQuery = setInterval(function() {
                    funcIntervalQuery();
                }, 15000);
            });
        }

        //查询交易结果. queryPayInfo返回的是一个Promise对象.
        function funcIntervalQuery() {
            nebPay.queryPayInfo(serialNumber, {
                    callback: app.chainnet.payApi
                })
                .then(function(resp) {
                    // console.log("tx result: " + resp) //resp is a JSON string
                    var respObject = JSON.parse(resp)
                    //code==0 交易发送成功, status==1 交易已被打包上链
                    if (respObject.code === 0 && respObject.data.status === 1) {
                        //交易成功,处理后续任务....
                        clearInterval(intervalQuery) //清除定时查询
                        swal('操作成功', '', 'success').then(function() {
                            window.location.reload();
                        });
                    } else if (respObject.data.status === 0) {
                        var errString = respObject.data.execute_error
                        if (errString !== '') {
                            clearInterval(intervalQuery) //清除定时查询
                            var error = JSON.parse(errString.substr(13));
                            swal('操作失败', error.msg, 'error');
                        }
                    }
                })
                .catch(function(err) {
                    console.log(err);
                });
        }

        function listener(resp) {
            console.log("response of push: " + JSON.stringify(resp))
            var respString = JSON.stringify(resp);
            if (respString.search("rejected by user") !== -1) {
                clearInterval(intervalQuery)
            } else if (respString.search("txhash") !== -1) {
                console.log("wait for tx result: " + resp.txhash)
            }
        }

        $(document).ready(function($) {
            'use strict';

            //to check if the extension is installed
            //if the extension is installed, var "webExtensionWallet" will be injected in to web page
            if (typeof(webExtensionWallet) === "undefined" && !isMobile()) {
                $('.app-body .container').prepend('<div class="alert alert-warning"><i class="fa fa-warning"></i> <strong>Oops!</strong> 您尚未在浏览器中安装<a href="https://github.com/ChengOrangeJu/WebExtensionWallet"><strong>【星云官方钱包插件】</strong></a>，无法正常使用安全交易功能！</div>');
                return;
            }

            $('#view-transaction').click(function() {
                var hash = $.trim($('input[name="hash"]').val());
                if (hash === '') {
                    swal('提示', '交易Hash不能为空，请重新输入！', 'warning');
                    return;
                }
                getTransaction(hash);
            });

            var hash = $.trim(Url.queryString('hash'));
            if (hash === '') {
                // $('input[name="hash"]').val(hash);
                $('#transaction-search-wrapper').removeClass('d-none');
            } else {
                getTransaction(hash);
            }



            // Url.updateSearchParam('hash', wallet || '');
        });
    </script>
</body>

</html>
